const { resolve } = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// 提取css文件
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

// 压缩css
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')

process.env.NODE_ENV = 'development'

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'build.js',
    path: resolve(__dirname, 'dist')
    // 需要添加publicPath,影响webpack-dev-server
    // publicPath: './'
  },
  // style-loader，创建style标签，将样式插入到body
  module: {
    rules: [
      {
        // 检查源码的风格
        // 安装 npm i -D eslint eslint-loader eslint-config-airbnb-base eslint-plugin-import
        test: /\.js$/,
        exclude: '/node_modules',
        loader: 'eslint-loader',
        options: {
          fix:true
        }
      },
      {
        test: /\.css$/,
        use: [
          // 提取js中的css成单独文件
          MiniCssExtractPlugin.loader,
          // 'style-loader',
          'css-loader',
          // css兼容性处理 postcss-loader postcss-preset-env
          // 帮postcss找到package.json中browserslist里面的配置，通过配置加载指定的css兼容性样式
          {
            loader: 'postcss-loader'
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          MiniCssExtractPlugin.loader,
          // 'style-loader',
          'css-loader',
          {
            loader: 'postcss-loader'
          },
          'less-loader'
        ]
      },
      {
        // test: /\.(jpg|png|gif)$/,
        test: /\.(jpg|png|gif)$/,
        loader: 'url-loader',
        options: {
          // 图片大小于小8KB，就会被base64处理
          limit: 8 * 1024,
          esModule: false,
          name: '[hash:10].[ext]'
        }
      },
      {
        // url-loader以es6模块化来解析图片，而html-loader以commonjs模块规范来解析
        test: /\.html$/,
        // 处理html的image图片
        loader: 'html-loader'
      },
      {
        exclude: /\.(css|js|html|less|json|jpg|png)$/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]'
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new MiniCssExtractPlugin({
      filename: 'css/main.css'
    }),

    new OptimizeCssAssetsWebpackPlugin()
  ],
  mode: 'development',
  // mode:'production'
  // 起一个server，只会在内存中编译打包，不会有输出
  // 启动指令 webpack-dev-server
  devServer: {
    contentBase: resolve(__dirname, 'dist'),
    compress: true,
    port: 3000,
    open: true
  }
}
